<!doctype html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>股票指数与新闻管理系统</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <link
            href="https://cdn.jsdelivr.net/npm/daisyui@4.12.14/dist/full.min.css"
            rel="stylesheet"
            type="text/css"
        />
        <link
            rel="stylesheet"
            href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
        />
        <style>
            .card {
                transition: all 0.3s ease;
            }
            .card:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            }
            .loading {
                position: relative;
            }
            .loading:after {
                content: "";
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(255, 255, 255, 0.8);
                display: flex;
                justify-content: center;
                align-items: center;
                background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='40' height='40' viewBox='0 0 50 50'%3E%3Cpath fill='%23333' d='M25,5A20.14,20.14,0,0,1,45,22.88a2.51,2.51,0,0,0,2.49,2.26h0A2.52,2.52,0,0,0,50,22.33a25.14,25.14,0,0,0-50,0,2.52,2.52,0,0,0,2.5,2.81h0A2.51,2.51,0,0,0,5,22.88,20.14,20.14,0,0,1,25,5Z'%3E%3CanimateTransform attributeName='transform' type='rotate' from='0 25 25' to='360 25 25' dur='0.6s' repeatCount='indefinite'/%3E%3C/path%3E%3C/svg%3E");
                background-repeat: no-repeat;
                background-position: center;
            }
        </style>
    </head>
    <body class="bg-gray-100 min-h-screen">
        <main class="container mx-auto px-4 py-8">
            <!-- 头部信息 -->
            <header class="text-center mb-8">
                <h1 class="text-3xl font-bold text-gray-800 mb-2">
                    股票指数与新闻管理系统
                </h1>
                <div class="flex justify-center items-center space-x-4">
                    <div class="text-lg text-gray-600">
                        <input
                            type="date"
                            id="current-date"
                            class="input input-bordered"
                        />
                    </div>
                    <div
                        class="badge badge-lg badge-primary text-white"
                        id="current-weekday"
                    ></div>
                </div>
            </header>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <!-- 股票指数管理部分 -->
                <div class="bg-white rounded-xl shadow-md p-6 card">
                    <h2
                        class="text-xl font-bold text-gray-800 mb-4 flex items-center"
                    >
                        <i class="fas fa-chart-line mr-2 text-green-500"></i>
                        股票指数管理
                    </h2>

                    <form id="stock-index-form" class="space-y-4">
                        <input type="hidden" value="" id="stock_id" />
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium">日期</span>
                            </label>
                            <input
                                type="date"
                                id="stock-date"
                                class="input input-bordered w-full"
                                required
                            />
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div class="form-control">
                                <label class="label">
                                    <span class="label-text font-medium"
                                        >开盘指数</span
                                    >
                                </label>
                                <input
                                    type="number"
                                    id="index-start"
                                    class="input input-bordered w-full"
                                    placeholder="开盘指数"
                                    required
                                />
                            </div>

                            <div class="form-control">
                                <label class="label">
                                    <span class="label-text font-medium"
                                        >午盘指数</span
                                    >
                                </label>
                                <input
                                    type="number"
                                    id="index-noon"
                                    class="input input-bordered w-full"
                                    placeholder="午盘指数"
                                    required
                                />
                            </div>

                            <div class="form-control">
                                <label class="label">
                                    <span class="label-text font-medium"
                                        >收盘指数</span
                                    >
                                </label>
                                <input
                                    type="number"
                                    id="index-end"
                                    class="input input-bordered w-full"
                                    placeholder="收盘指数"
                                    required
                                />
                            </div>
                        </div>

                        <div class="flex justify-end space-x-3 mt-6">
                            <button type="reset" class="btn btn-outline">
                                重置
                            </button>
                            <button type="submit" class="btn btn-primary">
                                提交指数数据
                            </button>
                        </div>
                    </form>
                </div>

                <!-- 新闻管理部分 -->
                <div class="bg-white rounded-xl shadow-md p-6 card">
                    <h2
                        class="text-xl font-bold text-gray-800 mb-4 flex items-center"
                    >
                        <i class="fas fa-newspaper mr-2 text-blue-500"></i>
                        新闻管理
                    </h2>

                    <form id="news-form" class="space-y-4">
                        <!-- 隐藏字段用于存储编辑中的新闻ID -->
                        <input type="hidden" id="editing-news-id" value="" />

                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >新闻标题</span
                                >
                            </label>
                            <input
                                type="text"
                                id="news-title"
                                class="input input-bordered w-full"
                                placeholder="输入新闻标题"
                                required
                            />
                        </div>

                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div class="form-control">
                                <label class="label">
                                    <span class="label-text font-medium"
                                        >日期</span
                                    >
                                </label>
                                <input
                                    type="date"
                                    id="news-date"
                                    class="input input-bordered w-full"
                                    required
                                />
                            </div>

                            <div class="form-control">
                                <label class="label">
                                    <span class="label-text font-medium"
                                        >国家/地区</span
                                    >
                                </label>
                                <select
                                    id="news-country"
                                    class="select select-bordered w-full"
                                    required
                                >
                                    <option value="" disabled selected>
                                        选择国家
                                    </option>
                                    <option value="CN">中国</option>
                                    <option value="Other">国际</option>
                                </select>
                            </div>
                        </div>

                        <div class="form-control">
                            <label class="label">
                                <span class="label-text font-medium"
                                    >新闻内容</span
                                >
                            </label>
                            <textarea
                                id="news-content"
                                class="textarea textarea-bordered h-24"
                                placeholder="输入新闻内容"
                                required
                            ></textarea>
                        </div>

                        <div class="flex justify-end space-x-3 mt-6">
                            <button
                                type="reset"
                                class="btn btn-outline"
                                id="news-reset-btn"
                            >
                                重置
                            </button>
                            <button
                                type="submit"
                                class="btn btn-primary"
                                id="news-submit-btn"
                            >
                                添加新闻
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 新闻列表 -->
            <div class="bg-white rounded-xl shadow-md p-6 mt-8 card">
                <h2
                    class="text-xl font-bold text-gray-800 mb-4 flex items-center"
                >
                    <i class="fas fa-list mr-2 text-purple-500"></i> 新闻列表
                </h2>

                <div class="overflow-x-auto">
                    <table class="table table-zebra w-full">
                        <thead>
                            <tr>
                                <th>日期</th>
                                <th>国家</th>
                                <th>标题</th>
                                <th>内容</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="news-table-body">
                            <!-- 新闻数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </main>

        <!-- 成功提示模态框 -->
        <dialog id="success_modal" class="modal">
            <div class="modal-box">
                <h3 class="text-lg font-bold text-green-600">操作成功!</h3>
                <p class="py-4" id="success_msg"></p>
                <div class="modal-action">
                    <form method="dialog">
                        <button class="btn">关闭</button>
                    </form>
                </div>
            </div>
        </dialog>

        <!-- 错误提示模态框 -->
        <dialog id="resp_modal" class="modal">
            <div class="modal-box">
                <h3 class="text-lg font-bold text-red-600" id="modal_title">
                    哎呀，真糟糕!
                </h3>
                <p class="py-4" id="msg"></p>
                <div class="modal-action">
                    <form method="dialog">
                        <button class="btn">关闭</button>
                    </form>
                </div>
            </div>
        </dialog>

        <script>
            // 全局变量，用于存储当前新闻列表
            let currentNewsList = [];

            document.addEventListener("DOMContentLoaded", function () {
                // 设置表单默认日期为今天
                setDefaultDates();

                // 绑定表单提交事件
                document
                    .getElementById("stock-index-form")
                    .addEventListener("submit", handleStockIndexSubmit);
                document
                    .getElementById("news-form")
                    .addEventListener("submit", handleNewsSubmit);

                // 绑定新闻表单重置事件
                document
                    .getElementById("news-reset-btn")
                    .addEventListener("click", resetNewsForm);

                // 绑定当前日期变化事件
                document
                    .getElementById("current-date")
                    .addEventListener("change", handleCurrentDateChange);

                // 加载初始数据
                loadCurrentDateData();
            });

            // 处理当前日期变化
            function handleCurrentDateChange() {
                updateWeekday();
                updateFormDates();
                loadCurrentDateData();
            }

            // 更新星期几显示
            function updateWeekday() {
                const dateInput = document.getElementById("current-date").value;
                const date = new Date(dateInput);
                const weekdays = [
                    "星期日",
                    "星期一",
                    "星期二",
                    "星期三",
                    "星期四",
                    "星期五",
                    "星期六",
                ];
                const weekdayStr = weekdays[date.getDay()];
                document.getElementById("current-weekday").textContent =
                    weekdayStr;
            }

            // 更新表单日期为当前选择的日期
            function updateFormDates() {
                const currentDate =
                    document.getElementById("current-date").value;
                document.getElementById("stock-date").value = currentDate;
                document.getElementById("news-date").value = currentDate;
            }

            // 加载当前日期对应的数据
            function loadCurrentDateData() {
                const currentDate =
                    document.getElementById("current-date").value;
                if (currentDate) {
                    fetchIndex(currentDate);
                    loadNews(currentDate);
                }
            }

            // 设置表单默认日期为今天
            function setDefaultDates() {
                const today = new Date().toISOString().split("T")[0];
                document.getElementById("current-date").value = today;
                document.getElementById("stock-date").value = today;
                document.getElementById("news-date").value = today;
                updateWeekday();
            }

            // 获取指定日期的股票指数
            async function fetchIndex(date) {
                try {
                    // 显示加载状态
                    document
                        .getElementById("stock-index-form")
                        .classList.add("loading");

                    // 将日期格式从 YYYY-MM-DD 转换为 YYYY-M-D 或保持原样，根据后端要求调整
                    const formattedDate = date.replace(/-/g, "-");
                    const res = await fetch("/market/stock/" + formattedDate);
                    console.log("Response:", res);

                    if (!res.ok) {
                        const errorData = await res.json();
                        throw new Error(
                            errorData.message ||
                                `HTTP error! status: ${res.status}`,
                        );
                    }

                    const result = await res.json();
                    console.log("API Response:", result);

                    if (result.status_code === 200 && result.data !== null) {
                        document.getElementById("stock_id").value =
                            result.data.id;
                        document.getElementById("index-start").value =
                            result.data.index_at_start;
                        document.getElementById("index-noon").value =
                            result.data.index_at_noon;
                        document.getElementById("index-end").value =
                            result.data.index_at_end;
                    } else {
                        // 如果没有数据，清空表单
                        document.getElementById("stock_id").value = "";
                        document.getElementById("index-start").value = "";
                        document.getElementById("index-noon").value = "";
                        document.getElementById("index-end").value = "";
                    }
                } catch (error) {
                    console.error(error);
                    showErrorModal("获取股市指数失败: " + error.message);
                } finally {
                    // 移除加载状态
                    document
                        .getElementById("stock-index-form")
                        .classList.remove("loading");
                }
            }

            // 处理股票指数表单提交
            async function handleStockIndexSubmit(e) {
                e.preventDefault();

                const stockIndexData = {
                    id: document.getElementById("stock_id").value
                        ? parseInt(document.getElementById("stock_id").value)
                        : null,
                    date: document.getElementById("stock-date").value,
                    index_at_start: parseInt(
                        document.getElementById("index-start").value,
                    ),
                    index_at_noon: parseInt(
                        document.getElementById("index-noon").value,
                    ),
                    index_at_end: parseInt(
                        document.getElementById("index-end").value,
                    ),
                };

                try {
                    const response = await fetch("/market/stock/index", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify(stockIndexData),
                    });

                    if (!response.ok) {
                        throw new Error(
                            `HTTP error! status: ${response.status}`,
                        );
                    }

                    const result = await response.json();

                    if (result.status_code === 200) {
                        showSuccessModal("股票指数数据保存成功！");
                        document.getElementById("stock-index-form").reset();
                        setDefaultDates();
                    } else {
                        throw new Error(result.message || "保存失败");
                    }
                } catch (error) {
                    console.error("Error:", error);
                    showErrorModal("保存股票指数数据失败: " + error.message);
                }
            }

            // 处理新闻表单提交
            async function handleNewsSubmit(e) {
                e.preventDefault();

                const editingNewsId =
                    document.getElementById("editing-news-id").value;
                const newsData = {
                    date: document.getElementById("news-date").value,
                    country: document.getElementById("news-country").value,
                    title: document.getElementById("news-title").value,
                    content: document.getElementById("news-content").value,
                };

                // 如果是编辑模式，添加ID
                if (editingNewsId) {
                    newsData.id = parseInt(editingNewsId);
                }

                try {
                    const response = await fetch("/market/stock/news", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                        },
                        body: JSON.stringify([newsData]),
                    });

                    if (!response.ok) {
                        throw new Error(
                            `HTTP error! status: ${response.status}`,
                        );
                    }

                    const result = await response.json();

                    if (result.status_code === 200) {
                        const message = editingNewsId
                            ? "新闻更新成功！"
                            : "新闻添加成功！";
                        showSuccessModal(result.message || message);
                        resetNewsForm();
                        setDefaultDates();
                        loadCurrentDateData(); // 重新加载当前日期的新闻列表
                    } else {
                        throw new Error(result.message || "保存失败");
                    }
                } catch (error) {
                    console.error("Error:", error);
                    showErrorModal(
                        (editingNewsId ? "更新" : "添加") +
                            "新闻失败: " +
                            error.message,
                    );
                }
            }

            // 重置新闻表单
            function resetNewsForm() {
                document.getElementById("news-form").reset();
                document.getElementById("editing-news-id").value = "";
                document.getElementById("news-submit-btn").textContent =
                    "添加新闻";
                setDefaultDates();
            }

            // 加载指定日期的新闻
            async function loadNews(date) {
                try {
                    // 显示加载状态
                    document.getElementById("news-table-body").innerHTML =
                        '<tr><td colspan="5" class="text-center">加载中...</td></tr>';

                    // 将日期格式从 YYYY-MM-DD 转换为 YYYY-M-D 或保持原样，根据后端要求调整
                    const formattedDate = date.replace(/-/g, "-");
                    const res = await fetch(
                        "/market/news/date/" + formattedDate,
                    );
                    console.log("Response:", res);

                    if (!res.ok) {
                        const errorData = await res.json();
                        throw new Error(
                            errorData.message ||
                                `HTTP error! status: ${res.status}`,
                        );
                    }

                    const result = await res.json();
                    console.log("API Response:", result);

                    if (result.status_code === 200 && result.data !== null) {
                        currentNewsList = result.data;
                        renderNewsTable(currentNewsList);
                    } else {
                        currentNewsList = [];
                        renderNewsTable(currentNewsList);
                    }
                } catch (error) {
                    console.error("Error loading news:", error);
                    showErrorModal("加载新闻列表失败: " + error.message);
                }
            }

            // 渲染新闻表格
            function renderNewsTable(newsList) {
                const tableBody = document.getElementById("news-table-body");
                tableBody.innerHTML = "";

                if (newsList.length === 0) {
                    tableBody.innerHTML =
                        '<tr><td colspan="5" class="text-center">暂无新闻数据</td></tr>';
                    return;
                }

                newsList.forEach((news) => {
                    const row = document.createElement("tr");
                    row.innerHTML = `
                <td>${news.date}</td>
                <td>${getCountryDisplayName(news.country)}</td>
                <td class="max-w-xs truncate">${news.title}</td>
                <td class="max-w-xs truncate">${news.content}</td>
                <td>
                    <button class="btn btn-sm btn-outline btn-info mr-2" onclick="editNews(${news.id})">编辑</button>
                    <button class="btn btn-sm btn-outline btn-error" onclick="deleteNews(${news.id})">删除</button>
                </td>
            `;
                    tableBody.appendChild(row);
                });
            }

            // 获取国家显示名称
            function getCountryDisplayName(countryCode) {
                const countryMap = {
                    CN: "中国",
                    Other: "国际",
                };
                return countryMap[countryCode] || countryCode;
            }

            // 编辑新闻
            function editNews(id) {
                // 从当前新闻列表中查找对应的新闻
                const news = currentNewsList.find((item) => item.id === id);
                if (!news) {
                    showErrorModal("未找到对应的新闻数据");
                    return;
                }

                // 填充表单数据
                document.getElementById("editing-news-id").value = news.id;
                document.getElementById("news-title").value = news.title;
                document.getElementById("news-date").value = news.date;
                document.getElementById("news-country").value = news.country;
                document.getElementById("news-content").value = news.content;

                // 更改按钮文本
                document.getElementById("news-submit-btn").textContent =
                    "更新新闻";

                // 滚动到新闻表单区域
                document
                    .getElementById("news-form")
                    .scrollIntoView({ behavior: "smooth" });
            }

            // 删除新闻
            async function deleteNews(id) {
                if (confirm("确定要删除这条新闻吗？")) {
                    try {
                        const res = await fetch(`/market/news/${id}`, {
                            method: "DELETE",
                        });
                        if (!res.ok) {
                            const errorData = await res.json();
                            throw new Error(
                                errorData.message ||
                                    `HTTP error! status: ${res.status}`,
                            );
                        }

                        const result = await res.json();
                        console.log("API Response:", result);

                        if (result.status_code === 200) {
                            showSuccessModal("新闻删除成功！");
                            loadCurrentDateData(); // 重新加载当前日期的新闻列表
                        } else {
                            throw new Error(result.message || "删除失败");
                        }
                    } catch (error) {
                        console.error("Error deleting news:", error);
                        showErrorModal("删除新闻失败: " + error.message);
                    }
                }
            }

            // 显示成功模态框
            function showSuccessModal(message) {
                document.getElementById("success_msg").textContent = message;
                document.getElementById("success_modal").showModal();
            }

            // 显示错误模态框
            function showErrorModal(message) {
                document.getElementById("msg").textContent = message;
                document.getElementById("resp_modal").showModal();
            }
        </script>
    </body>
</html>
